package icu.ac.kr.simpleRssReader.provider;

import icu.ac.kr.simpleRssReader.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.util.Log;

public class RssDBProvider extends ContentProvider {

	SQLiteDatabase sqlDB;
	static final String TAG = "RssDBProvider";
	
	static final UriMatcher URIMATCHER;
	
	static final int CHANNEL = 1;
	static final int POST = 2;
	static final int CHANNELID = 3;
	static final int POSTID = 4;
	
	static {
		
		URIMATCHER = new UriMatcher(0);
		URIMATCHER.addURI(RssDBProviderConstant.AUTHORITY, "channels", CHANNEL);
		URIMATCHER.addURI(RssDBProviderConstant.AUTHORITY, "posts", POST);
		URIMATCHER.addURI(RssDBProviderConstant.AUTHORITY, "channels/#", CHANNELID);
		URIMATCHER.addURI(RssDBProviderConstant.AUTHORITY, "posts/#", POSTID);
		
	}
	
	private class DBOpenHelper extends SQLiteOpenHelper{

		public DBOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			
			db.execSQL("create table channels(_id integer primary key, title text unique, url text unique);");
			db.execSQL("create table posts(_id integer primary key, channel_id integer, pubdate text, title text unique, url text unique, body text, read integer(1) default '0');");
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub

			onCreate(db);
			
		}
		
	}
	
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		Uri notiuri = null;
	 	
		switch(URIMATCHER.match(uri))
		{
		case CHANNEL:
			Log.d(TAG, "channel deleted");
			sqlDB.delete("channels", selection, null);
			break;
		case POST:
			Log.d(TAG, "post deleted");
			sqlDB.delete("posts", selection, null);
			break;
		}
		
		getContext().getContentResolver().notifyChange(uri, null);
		return 0;
	}

	private void makeDefaultICON(String filename){
		
		Resources resource = getContext().getResources();
		InputStream input = resource.openRawResource(R.drawable.icon);
		
		try {
			OutputStream output = getContext().openFileOutput(filename, Context.MODE_WORLD_READABLE);
			byte[] by = new byte[1024];
			
			while(true)
			{
				int read = input.read(by);
				if (read < 0) break;
				output.write(by, 0, read);
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	/*
	 *  currently all channel icons are same. default one.
	 * 
	 * (non-Javadoc)
	 * @see android.content.ContentProvider#openFile(android.net.Uri, java.lang.String)
	 */
	
	@Override
	public ParcelFileDescriptor openFile(Uri uri, String mode)
			throws FileNotFoundException {
		// TODO Auto-generated method stub

		int imode = 0;
		File file = new File(getContext().getFileStreamPath("ICON").getAbsolutePath());
		 
		if (mode.equals("r"))
		{
			imode |= ParcelFileDescriptor.MODE_READ_ONLY; 
			Log.d(TAG, "reading");
	
			if (file.exists() == false)
			{
				makeDefaultICON("ICON");
			}
		}
		else
		{
			Log.d(TAG, "writing");
			imode |= ParcelFileDescriptor.MODE_CREATE;
		    imode |= ParcelFileDescriptor.MODE_READ_WRITE;
			
		}
		
		return ParcelFileDescriptor.open(file, imode);
	
	
	}

 	
	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
	
		String ret = null;
		
		switch (URIMATCHER.match(uri))
		{
		case CHANNEL:
			ret = "rssreader.icu.ac.kr/channels";
			break;
		case CHANNELID:
			ret = "rssreader.icu.ac.kr.dir/posts";
			break;
		case POSTID:
			ret = "rssreader.icu.ac.kr.item/posts";
			break;
		
		}
		
		
		return ret;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		Uri notiuri = null;
		long id = 0;
		Log.d(TAG, "insert 1");
		switch(URIMATCHER.match(uri))
		{
		case CHANNEL:
			Log.d(TAG, "insert CHANNEL");
			id = sqlDB.insert("channels", null, values);
			notiuri = ContentUris.withAppendedId(uri, id);
			break;
		case POST:
			Log.d(TAG, "insert POST");
			id = sqlDB.insert("posts", null, values);
			notiuri = ContentUris.withAppendedId(uri, id);
			break;
		
			
		}
		
		getContext().getContentResolver().notifyChange(notiuri, null);
		
		return notiuri;
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		
		DBOpenHelper dbHelper = new DBOpenHelper(getContext(),"rssreader.db", null, 1);
		sqlDB = dbHelper.getWritableDatabase();
		
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		
		Cursor cursor = null;
		
		switch(URIMATCHER.match(uri))
		{
		case CHANNEL:
			cursor = sqlDB.query("channels", projection, selection, null, null, null, null);
			break;
		case POST:
			cursor = sqlDB.query("posts", projection, selection, null, null, null, null);
			break;
		case CHANNELID:
			cursor = sqlDB.query("posts", projection, selection, null, null, null, null);
			break;
		case POSTID:
			cursor = sqlDB.query("posts", projection, selection, null, null, null, null);
			break;
		
		}
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		sqlDB.update("posts", values, selection, null);
		
		return 0;
	}

}
